import store from '@/store'
import router from '@/router'

export default async (url = '', data = {}, type = 'GET', method = 'fetch') => {
    type = type.toUpperCase()
    url = process.env.BASE_API + url
    if (type === 'GET') {
        let dataStr = '' // 数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&'
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
            url = url + '?' + dataStr
        }
    }
    if (window.fetch && method === 'fetch') {
        let requestConfig = {
            // credentials: 'include',
            method: type,
            headers: {
                'Accept': 'x-requested-with',
                'Content-Type': 'application/json;charset=utf-8',
            },
            mode: "cors",
        }

        if (type === 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        } 
        try {        
            const response = await fetch(url, requestConfig)
            const responseJson = await response.json()
            if(responseJson.code == 10000){
                return Promise.resolve(responseJson)
            }else if(responseJson.code == 10001){
                localStorage.removeItem("token");
                store.state.goods.useInfo.token = '';
                router.push('/login');		
                location.reload();
            }else{
                return Promise.reject(responseJson)
            }
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest()
            } else {
                requestObj = new ActiveXObject()
            }

            let sendData = ''
            if (type === 'POST') {
                sendData = JSON.stringify(data)
            }
            requestObj.setRequestHeader('Content-type', 'application/json;charset=utf-8')
            requestObj.setRequestHeader('Accept', 'application/json')
            requestObj.withCredentials = true;
            requestObj.send(sendData)
            requestObj.onreadystatechange = () => {
                if (requestObj.readyState === 4) {
                    if (requestObj.status === 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj)
                        }
                        if(obj.code == 10000){
                            resolve(obj)
                        }else if(obj.code == 10001){
                            localStorage.removeItem("token");
                            store.state.goods.useInfo.token = '';
                            this.$router.push('/login');		
                        }else{
                            reject(requestObj)
                        }                     
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}
